package com.simple.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.simple.common.PageResult;
import com.simple.common.Result;
import com.simple.dto.AmountDTO;
import com.simple.dto.BillDTO;
import com.simple.dto.FundDTO;
import com.simple.mapper.AmountMapper;
import com.simple.mapper.BankMapper;
import com.simple.mapper.FundMapper;
import com.simple.pojo.Amount;
import com.simple.pojo.Bank;
import com.simple.pojo.Bill;
import com.simple.pojo.Fund;
import com.simple.service.AmountService;
import com.simple.utils.BeanConverterUtil;
import com.simple.utils.SimpleUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName AmountServiceImpl
 * @Author SimpleTree
 **/
@Service
@Transactional(rollbackFor = Exception.class)
public class AmountServiceImpl implements AmountService {
    @Resource
    private AmountMapper amountMapper;
    @Resource
    private FundMapper fundMapper;
    @Resource
    private BankMapper bankMapper;
    @Autowired
    private BeanConverterUtil beanConverterUtil;

    @Override
    public Double getTotalMoney(Integer userId) {
        //根据userId获取最新总金额
        List<Amount> amounts = amountMapper.getLatestAmountsByUserId(userId);
        if (CollUtil.isEmpty(amounts)) {
            return 0D;
        }
        Amount amount = amounts.get(0);

        //开始相加
        return getTotalMoney(new BigDecimal("0"),amount.getWx(), amount.getZfb(), amount.getWxFund(), amount.getZfbFund(),amount.getBank());
    }

    @Override
    public PageResult getAmounts(AmountDTO amountDTO) {
        PageHelper.startPage(amountDTO.getPageNum(), amountDTO.getPageSize());
        List<Amount> amounts = amountMapper.getLatestAmountsByUserId(amountDTO.getUserId());
        PageInfo<Amount> amountsPageInfo = new PageInfo<>(amounts);
        List<AmountDTO> amountDTOs = new ArrayList<>();

        for (Amount amount : amounts) {
            AmountDTO dto = beanConverterUtil.toAmountDTO(amount);
            String desc = amount.getDescription();

            //描述翻译
            if (StringUtils.isNotEmpty(desc)) {
                String[] split = desc.split("=");
                if (split != null && split.length == 3) {
                    dto.setWxFunds(fundMapper.getFundsByIds(SimpleUtil.arr2List(split[0])));
                    dto.setZfbFunds(fundMapper.getFundsByIds(SimpleUtil.arr2List(split[1])));
                    dto.setBanks(bankMapper.getBanksByIds(SimpleUtil.arr2List(split[2])));
                }
            }

            //总金额
            dto.setTotalMoney(getTotalMoney(new BigDecimal("0"),amount.getWx(), amount.getZfb(), amount.getWxFund(), amount.getZfbFund(),amount.getBank()));

            amountDTOs.add(dto);
        }

        return new PageResult(amountsPageInfo.getTotal(), amountsPageInfo.getPageNum(), amountDTOs);
    }

    @Override
    public AmountDTO getAmountById(Integer id) {
        Amount amount = amountMapper.selectByPrimaryKey(id);
        return beanConverterUtil.toAmountDTO(amount);
    }

    public BigDecimal getBanksMoney(List<Bank> banks) {
        BigDecimal initMoney = new BigDecimal("0.00");
        if (CollUtil.isNotEmpty(banks)) {
            for (Bank bank : banks) {
                initMoney = initMoney.add(new BigDecimal(bank.getMoney() + ""));
            }
        }
        return initMoney;
    }

    public Double getTotalMoney(BigDecimal money, Double wx, Double zfb, Double wxFund, Double zfbFund,Double bank) {
        return (money.add(new BigDecimal(wx + ""))
                .add(new BigDecimal(zfb + ""))
                .add(new BigDecimal(wxFund + ""))
                .add(new BigDecimal(zfbFund + ""))
                .add(new BigDecimal(bank + ""))).doubleValue();
    }


    @Override
    public void saveAmount(AmountDTO amountDTO) {
        Amount amount = beanConverterUtil.toAmount(amountDTO);
        amount.setCreateTime(new Date());
        amount.setUpdateTime(new Date());

        StringBuilder wxFundDesc = new StringBuilder();
        StringBuilder zfbFundDesc = new StringBuilder();
        //计算基金总额
        List<Fund> funds = fundMapper.getFunds(amountDTO.getUserId(), null, -1);

        BigDecimal wxFund = new BigDecimal("0");
        BigDecimal zfbFund = new BigDecimal("0");
        for (Fund fund : funds) {
            if (fund.getLocation() == 1) {
                wxFund = wxFund.add(new BigDecimal(fund.getProfit() + ""));
                wxFundDesc.append(fund.getId()).append("-");
            } else if (fund.getLocation() == 2) {
                zfbFund = zfbFund.add(new BigDecimal(fund.getProfit() + ""));
                zfbFundDesc.append(fund.getId()).append("-");
            } else {
                continue;
            }
        }

        amount.setWxFund(wxFund.doubleValue());
        amount.setZfbFund(zfbFund.doubleValue());

        //获取最新的所有银行卡
        List<Bank> banks = bankMapper.getLatestBanksByUserId(amountDTO.getUserId());
        amount.setBank(getBanksMoney(banks).doubleValue());

        String bankDesc = banks.stream().map(bank -> bank.getId() + "-").collect(Collectors.joining());
        if (StringUtils.isNotEmpty(bankDesc)) {
            bankDesc = bankDesc.substring(0, bankDesc.length() - 1);
        }

        //描述
        if (StringUtils.isNotEmpty(wxFundDesc.toString())) {
            wxFundDesc.deleteCharAt(wxFundDesc.length() - 1);
        }
        if (StringUtils.isNotEmpty(zfbFundDesc.toString())) {
            zfbFundDesc.deleteCharAt(zfbFundDesc.length() - 1);
        }

        amount.setDescription(wxFundDesc.toString() + "=" + zfbFundDesc.toString() + "=" + bankDesc);

        //插入存款
        amountMapper.insertSelective(amount);

    }

    @Override
    public void updateAmount(AmountDTO amountDTO) {
        //总金额更新
        Amount amount = beanConverterUtil.toAmount(amountDTO);
        amountMapper.updateByPrimaryKeySelective(amount);
    }

    @Override
    public void deleteByIds(List<Integer> ids) {
        amountMapper.deleteByIds(ids);
    }

}
